#    This file is part of robo-ircbot.
#
#    robo-ircbot is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    robo-ircbot is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with robo-ircbot.  If not, see <http://www.gnu.org/licenses/>.

package App::Modular::Module::BombzCount;
use strict;
use warnings;
use LWP::Simple;
use base qw(App::Modular::Module);

print ":: BombzCount module loaded.\n";

# Events we want to receive.
sub events { return "PRIVMSG"; }

sub help {
        return (
                "Retrieve download statistics for the FOSS community's favorite ".
                "past-time.",
                "bombzcounter"
        );
}

# PRIVMSG events.
sub event_privmsg
{
        shift;
        my $e = shift;

        my $help = $e->robo->mod("Helper") || return;
        my $nick = $help->parse_nick($e->from);

        # Admin commands for bombzcounter module.
        if ($help->trigger_switch("bombzcounter", $e)) {
                return;
        }

        # Bombzcounter trigger.
        if (my $h = $help->trig("bombzcounter", $e)) {
                get_bombzcount($e);
        }
}

# Get the bombz download count.
sub get_bombzcount
{
        my $e = shift;

        # Retrieve google projects page count
        my $content = get("http://code.google.com/p/bombz-gtk/downloads/list");
        $content =~ s/[\n\r]//g;
        $content =~ s/\s{2,}//g;

        my @filez = ();

        while ($content =~ m/<td class=\"vt id col_0\">\s*<a href=\"(\S+)\".*?>\s*([\w\.\!\-\+]+)\s*<\/a>/g) {
                push(@filez, [$1, $2, 0]);
        }

        my $count = 0;
        while ($content =~ m/<td class=\"vt col_4\".*?>\s*<a onclick=\"cancelBubble=true;\" href=\"(\S+)\".*?>\s*(\d+)\s*<\/a>/g) {
                $filez[$count++]->[2] = $2;
        }

        foreach (@filez) {
                $e->s("PRIVMSG ".$e->dest." :".$_->[1]." (".$_->[0].") \002".$_->[2]." downloads\002");
                sleep(1);
        }

        # Retrieve AUR count
        $content = get("http://aur.archlinux.org/packages.php?ID=21082");
        $content =~ s/[\n\r]//g;
        $content =~ s/\s{2,}//g;

        $content =~ /<span class='f3'>Votes: (\d+)<\/span>/;
        $e->s("PRIVMSG ".$e->dest." :AUR: \002".$1." votes\002");
}

1;
